package web;/**
 * @author 王俊彪
 * @version 1.0
 */

import beans.LoginStatus;
import beans.User;
import service.UserService;
import utils.ResultUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取页面传递的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //将用户数据进行封装，方便将来传递给service层
        User user = new User(username, password);
        //调用UserService处理业务逻辑:登录逻辑处理
        UserService userService = new UserService();
        User existUser = userService.login(user);
        //根据exisUser响应的结果 返回信息
        String responseData;//存储响应数据
        if(existUser!=null){
            //说明登录成功
            //将用户信息（会话状态）存储在session中
            request.getSession().setAttribute("existUser",existUser);
            //登录成功并且勾选了记住我复选框，此时向浏览器写一个cookie
            //该cookie记录用户信息
            String autoLogin = request.getParameter("autoLogin");
            if(autoLogin!=null && "on".equals(autoLogin)){
                Cookie cookie = new Cookie("autoLogin", username + "#" + password);
                cookie.setMaxAge(7*24*60*60);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
            //构造登录成功的响应数据
            responseData=ResultUtils.result(LoginStatus.LOGIN_SUCCESS,existUser);
        }else{
            //说明登录失败,构造登录失败的响应数据
            //new User(username,password)构造的是登录失败的数据
            responseData=ResultUtils.result(LoginStatus.LOGIN_FAIL,new User(username,password));
        }
        //返回响应数据
        response.getWriter().write(responseData);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
